﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RooHui.Infrastructure.Entities.Entity;
using RooHui.Portal.WebLogic;
using RooHui.Portal.Biz;
using RooHui.Infrastructure.Entities.Enum;
using System.Text.RegularExpressions;
using RooHui.Tool;
using RooHui.Portal.Biz.Model;
using RooHui.Infrastructure.Entities;
using RooHui.Application.CommonWebLogic;
using RooHui.Portal.Web.Model;

namespace RooHui.Portal.Web.Controllers
{
    [Auth(MemberType.Invester)]
    public class MemberController : MemberBaseController
    {
        //
        // GET: /Member/

        public ActionResult Index()
        {
            ViewBag.MemberLog = MemberBiz.GetLastMemberLog(HttpContext.User.Identity.Name, MemberOperateType.Login);
            ViewBag.Investment = InvestmentBiz.GetMemberInvestmentInfo(HttpContext.User.Identity.Name);
            ViewBag.Repayment = InvestmentBiz.GetMemberRepaymentInfo(HttpContext.User.Identity.Name);
            ViewBag.Capital = MemberBiz.GetCapitalInfo(HttpContext.User.Identity.Name);
            ViewBag.AccountOperations = MemberBiz.GetAccountOperations(HttpContext.User.Identity.Name, "", "", 0, 4);
            return View();
        }

        #region 信息认证
        public ActionResult SetMobile()
        {
            return View();
        }
        [HttpPost]
        public ActionResult SetMobile(string mobile, string mobilecode)
        {
            if (SupportBiz.CheckShortMessageCode(HttpContext.User.Identity.Name, mobilecode, CheckCodeType.SetMobileShortMessageCode))
            {
                var member = (Member)ViewBag.Member;
                if (!member.HandPhoneCheck)
                {
                    member.HandPhone = mobile;
                    member.HandPhoneCheck = true;
                    member.PostModify();
                    return RedirectToAction("index");
                }
            }
            else
            {
                ViewBag.Message = "验证码错误，请重新输入！";
            }
            return View();
        }
        public string GetCodeForSetMobile(string username,string mobile)
        {
            if (new Regex("^1\\d{10}$").IsMatch(mobile))
            {
                SupportBiz.SendShortMessageCode(username, mobile, CheckCodeType.SetMobileShortMessageCode);
                return "1";
            }
            return "0";
        }
        public ActionResult Setauth()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Setauth(string CardId)
        {
            string page1 = processIDCardUpLoad("page1", "page1");
            string page2 = processIDCardUpLoad("page2", "page2");
            if (!String.IsNullOrEmpty(page1) && !String.IsNullOrEmpty(page2))
            {
                MemberBiz.SetMemberAuth(HttpContext.User.Identity.Name, CardId, page1, page2);
                return RedirectToAction("index");
            }
            ViewBag.Message = "保存失败，请稍后重试！或联系在线客服";
            return View();
        }
        private string processIDCardUpLoad(string controlName,string token)
        {
            var file = Request.Files[controlName];
            string userName = HttpContext.User.Identity.Name;
            string fileNewName = String.Format("Temp_IDCard_{0}_{1}_{2}{3}", DateTime.Now.ToString("yyMMdd"), userName,token,
                new System.IO.FileInfo(file.FileName).Extension);
            ImagePlug.SaveAndZoom(file, Server.MapPath("~/Resource/Temp/" + fileNewName));
            if (System.IO.File.Exists(Server.MapPath("~/Resource/Temp/" + fileNewName)))
            {
                return "/Resource/Temp/" + fileNewName;
            }
            return string.Empty;
        }
        #endregion

        #region 账户设置
        public ActionResult MemberInfo()
        {
            return View();
        }
        public ActionResult Security()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Security(string password, string newpassword, string confirm)
        {
            var member = (Member)ViewBag.Member;
            if (member.Password == AesAlgorithm.Encrypt(password))
            {
                if (newpassword == confirm)
                {
                    member.Password = AesAlgorithm.Encrypt(newpassword);
                    member.PostModify();
                    ViewBag.Sueess = true;
                    return View();
                }
                else
                {
                    ViewBag.Sueess = false;
                    ViewBag.Message = "两次密码输入不一致，请重新输入！";
                    return View();
                }
            }
            else 
            {
                ViewBag.Sueess = false;
                ViewBag.Message = "原密码输入错误！请重新输入";
                return View();
            }
        }
        public ActionResult Notice(int page =0)
        {
            return View();
        }
        public ActionResult Coupon()
        {
            return View();
        }
        #endregion

        #region 充值/提现
        public ActionResult Recharge()
        {
            ViewBag.Account = MemberBiz.GetAccount(HttpContext.User.Identity.Name);
            return View();
        }
        [HttpPost]
        public ActionResult Recharge(string bankID, decimal rechargeAmount)
        {
            if (String.IsNullOrEmpty(bankID) || rechargeAmount <= 1)
            {
                ViewBag.Account = MemberBiz.GetAccount(HttpContext.User.Identity.Name);
                ViewBag.Message = "您的输入有误，请重新选择！";
                return View();
            }
            Member member = ViewBag.Member;
            if (!member.IsActive)
            {
                ViewBag.Account = MemberBiz.GetAccount(HttpContext.User.Identity.Name);
                ViewBag.Message = "请先完成帐户激活！";
                return View();
            }
            if (member.Status != ItemStatus.Enable)
            {
                ViewBag.Account = MemberBiz.GetAccount(HttpContext.User.Identity.Name);
                ViewBag.Message = "您的帐户不可用，请联系客服！";
                return View();
            }
            if (!member.IDCardCheck)
            {
                ViewBag.Account = MemberBiz.GetAccount(HttpContext.User.Identity.Name);
                ViewBag.Message = "请先完成帐户实名认证！";
                return View();
            }
            return RedirectToAction("RechargeRedirect", new
            {
                token = RooHui.Tool.EncodeByBase64.Encode(new RechargeRedirectModel()
                {
                    BankID = bankID,
                    Amount = rechargeAmount
                }.ToJson())
            });
        }
        public ActionResult RechargeRedirect(string token)
        {
            var model = EncodeByBase64.Decode(token).ToObject<RechargeRedirectModel>();
            if (model == null || String.IsNullOrEmpty(model.BankID) || model.Amount <= 1)
            {
                return RedirectToAction("Recharge");
            }
            Member member = ViewBag.Member;
            if (!member.IsActive)
            {
                return RedirectToAction("Recharge");
            }
            if (member.Status != ItemStatus.Enable)
            {
                return RedirectToAction("Recharge");
            }
            if (!member.IDCardCheck)
            {
                return RedirectToAction("Recharge");
            }
            ViewBag.BankId = model.BankID;
            ViewBag.Amount = model.Amount;
            return View();
        }
#if DEBUG
        /// <summary>
        /// 测试临时使用
        /// </summary>
        /// <param name="bankID"></param>
        /// <param name="amount"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult rechargecallback(string bankID, decimal amount)
        {
            var account1 = MemberBiz.GetAccount(HttpContext.User.Identity.Name);
            var account2 = Account.ChangeAccount(HttpContext.User.Identity.Name, amount, 0);
            var operation = new AmountOperation()
            {
                Amount = amount,
                Bank = bankID,
                CreateTime = DateTime.Now,
                IpAddress = HttpContext.Request.ServerVariables["REMOTE_ADDR"],
                IsSuccess = true,
                OperationType = AmountOperationType.Recharge,
                PayBackTime = DateTime.Now,
                ResultCode = "200",
                Status = ItemStatus.Enable,
                UserName = HttpContext.User.Identity.Name
            }.PostAdd();
            new AmountHistory()
            {
                AmountOperationID = operation.ID,
                ChangeValue = amount,
                CreateTime = DateTime.Now,
                CurrentAmount = account2.BalanceAmount,
                CurrentFreeze = account2.FrozenAmount,
                OperationType = AmountOperationType.Recharge,
                PreAmount = account1.BalanceAmount,
                PreFreeze = account1.FrozenAmount,
                UserName = HttpContext.User.Identity.Name,
                TransactionUser = HttpContext.User.Identity.Name
            }.PostAdd();
            return RedirectToAction("Index");
        }
#endif
        public ActionResult Withdraw()
        {
            ViewBag.Account = MemberBiz.GetAccount(HttpContext.User.Identity.Name);
            return View();
        }
        [HttpPost]
        public ActionResult withdraw(decimal amount, string validationCode)
        {
            if (!ValidateValidateCode(validationCode))
            {
                ViewBag.Amount = amount;
                ViewBag.Account = MemberBiz.GetAccount(HttpContext.User.Identity.Name);
                ViewBag.Message = "验证码输入有误，请重新输入！";
                return View();
            }
            if (!Account.CheckBalanceAmount(HttpContext.User.Identity.Name, amount))
            {
                ViewBag.Account = MemberBiz.GetAccount(HttpContext.User.Identity.Name);
                ViewBag.Message = "您的帐户余额不足！";
                return View();
            }
            return RedirectToAction("withdrawredirect", new { token = EncodeByBase64.Encode(amount.ToString()) });
        }
        public ActionResult WithdrawRedirect(string token)
        {
            decimal amount = 0;
            if (!decimal.TryParse(EncodeByBase64.Decode(token), out amount))
            {
                return RedirectToAction("Withdraw");
            }
            if (!Account.CheckBalanceAmount(HttpContext.User.Identity.Name, amount))
            {
                return RedirectToAction("Withdraw");
            }
            ViewBag.Amount = amount;
            return View();
        }
#if DEBUG
        [HttpPost]
        public ActionResult withdrawcallback(decimal amount)
        {
            var account1 = MemberBiz.GetAccount(HttpContext.User.Identity.Name);
            var account2 = Account.ChangeAccount(HttpContext.User.Identity.Name, -amount, 0);
            if (account2 != null)
            {
                var operation = new AmountOperation()
                {
                    Amount = amount,
                    CreateTime = DateTime.Now,
                    IpAddress = HttpContext.Request.ServerVariables["REMOTE_ADDR"],
                    IsSuccess = true,
                    OperationType = AmountOperationType.Withdraw,
                    PayBackTime = DateTime.Now,
                    ResultCode = "200",
                    Status = ItemStatus.Enable,
                    UserName = HttpContext.User.Identity.Name
                }.PostAdd();
                new AmountHistory()
                {
                    AmountOperationID = operation.ID,
                    ChangeValue = amount,
                    CreateTime = DateTime.Now,
                    CurrentAmount = account2.BalanceAmount,
                    CurrentFreeze = account2.FrozenAmount,
                    OperationType = AmountOperationType.Withdraw,
                    PreAmount = account1.BalanceAmount,
                    PreFreeze = account1.FrozenAmount,
                    UserName = HttpContext.User.Identity.Name,
                    TransactionUser = HttpContext.User.Identity.Name
                }.PostAdd();
            }
            return RedirectToAction("Index");
        }
#endif
        /// <summary>
        /// 验证验证码是否正确
        /// </summary>
        /// <returns></returns>
        private bool ValidateValidateCode(string code)
        {
            bool result;

            string token = Request.Params["token"];
            if (token == null)
            {
                result = false;
            }
            else
            {
                token = Cryptogram.CommonEncrypt(token);
                //过虑加密后出现的非法字符
                token = token.Replace("/", "");
                token = token.Replace("+", "");
                token = token.Replace("=", "");
                token = token.Substring(0, 4).ToString();
                token = token.ToLower();
                //过虑0为O,I和1
                token = token.Replace("0", "o");
                token = token.Replace("1", "i");
                string validStr = code.ToLower();
                //o,0转换，i,1转换
                validStr = validStr.Replace("0", "o");
                validStr = validStr.Replace("1", "i");
                if (validStr != token)
                    result = false;
                else
                    result = true;
            }
            return result;
        }
        #endregion

        public ActionResult Invest(int page = 0, int type = 0, string start = "",string end = "")
        {
            ItemListBox<InvestmentItemsModel> data = InvestmentBiz.GetMemberInvestmentList(HttpContext.User.Identity.Name,
                type, start, end, page, 25);
            ViewBag.Investments = data;
            return View();
        }

        public ActionResult OrderDetail(int Id)
        {
            var order =InvestmentBiz.GetOrderDetail(Id, HttpContext.User.Identity.Name);;
            ViewBag.OrderDetail = order;
            var list = ProjectBiz.InvestmentRepaymentCalculate(order.ProjectId, order.ProjectInvests.Sum(c => c.InvestMentAmount));
            ViewBag.Plan = list.GroupBy(c => c.PayBackDate).OrderBy(c => c.Key).ToList();
            return View();
        }

        public ActionResult Activity(int page = 0, string start="", string end="")
        {
            ViewBag.Operations = MemberBiz.GetAccountOperations(HttpContext.User.Identity.Name, start, end, page);
            return View();
        }

        public ActionResult Repayment(int page = 0,int projectId =0, string start = "", string end = "")
        {
            ViewBag.PayBackItems = InvestmentBiz.GetPayBackItems(HttpContext.User.Identity.Name,projectId, start, end, page);
            ViewBag.InvestProjectNames = InvestmentBiz.GetInvestProjectNames(HttpContext.User.Identity.Name);
            return View();
        }
        
    }
}
